
// 引入接口文件
import {regionArea,getProduct, queryAllAddress,queryEstateList,sumbit,update,queryDetail,queryBankCodeList } from './accountDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { makeAddress } from "utils/util"
import AppBus from '../../../utils/bus'

// 初始默认状态
const defultState = {
  loading: false,
  btnLoading: false,
  accountDetail:{
    cityCode:[],
    type:'1',
    regionId:null
  },
  actionType:'',
  estateList:[],
  disabled:false,
  bankCodeList:[],
  areaList:[],
  area1:[],
  areas:[],
  products:[],
  roleType:'',
  show:true,
}

// 声明module
const tmpModule = {
 
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        let { actionType, id } = query
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
        
          dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
          dispatch({ type: 'updateStore', payload: { actionType,roleType:localStorage.getItem('roleType')} });
          dispatch({ type: 'getAreaList', payload: {} });
          dispatch({ type: 'regionArea', payload: {} });
          dispatch({ type: 'queryBankCodeList', payload: {} });
          if(actionType=='check'||actionType=='edit'){
            dispatch({
              type:'queryDetail',
              payload:{id}
            })
            
          }
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    // 查询记录
    *getAreaList({ payload }, { put, call, select }){
      const { data, success } = yield call(queryAllAddress);
      if(success) {
          let areaList = []
          let arr = [data[0]]
          let attr = [data[data.length-1]]
          // data[0] = {
          //   label:"北京",
          //   value:"110100",
          //   children:arr
          // }
          // data[data.length-1]={
          //   label:"澳门",
          //   value:"820000",
          //   children:attr
          // }
          //去掉第三级，
          areaList = makeAddress(data,2)
        yield put({ type: 'updateStore',payload:{areaList}})
      }
    },
    *regionArea({payload},{put,call,select}){
			let {accountDetail,areas}=yield select(state => state[tmpModule.namespace])
			const {success,data}=yield call(regionArea)
			if(success){
        if(accountDetail.regionId){
          data.map((item,index)=>{
            if(item.value==accountDetail.regionId){
              areas = makeAddress(item.children,2)
              areas.shift()
            }
          })
          yield put({
            type:'getProduct',
            payload:{}
          })
        }
				yield put({type:'updateStore',payload:{area1:data,areas}})
			}
		},
		*getProduct({payload},{put,call,select}){
      let {products,accountDetail} = yield select(state => state[tmpModule.namespace])
        if(accountDetail.city){
          const { data, success } = yield call(getProduct,{cityCode:accountDetail.city});
          if(success){
            products=data
            yield put({ type: 'updateStore',payload:{products}})
          }
        }
		  },
    //楼盘列表
    *getEstateList({ payload }, { put, call, select }) {
      try {
        let tmpState = yield select(state => state[tmpModule.namespace])
        let { accountDetail } = tmpState
        const { resolve,typeGet } = payload;
        let params = {
          pageNo: 1,
          pageSize: 1000,
          ...payload
        }
        const data = yield call(queryEstateList, params)
        let estateList = data.rows
        if (data.success) {
          yield put({ type: 'updateStore', payload: { estateList} });
        }
        
      } catch (e) {
        console.log(e)
      }
    },
    
    //提交
    *sumbit({payload},{ put, call, select }){
      try {
        let tmpState = yield select(state => state[tmpModule.namespace])
        let { accountDetail,actionType } = tmpState
        console.log(accountDetail)
        const data = yield call(actionType == 'add'?sumbit : update,  accountDetail )
        if (data.success) {
          message.success(actionType == 'add'?'提交成功':'编辑成功').then(() => {
            let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
            console.log(urlArray)
            AppBus.emit('closeTab', {
              key: urlArray[0],
              cbf: () => {
                hashHistory.push(urlArray[1])
              }
            })
          });
        }
      } catch (e) {
        console.log(e)
      }
    },
    //查询
    *queryDetail({payload},{ put, call, select }){
      try {
        
        const {data,success} = yield call(queryDetail,  payload.id )
        if (success) {
          // data.accountType = "公户"//todo hardCode
          data.cityCode=[data.province,data.city]
          yield put({ type: 'updateStore', payload: {accountDetail:data} });
          yield put({ type: 'getEstateList', payload: {city:data.city,province:data.province} });
          yield put({ type: 'regionArea', payload: {} });
        }
        
      } catch (e) {
        console.log(e)
      }
    },
    //银行列表
    *queryBankCodeList({payload},{ put, call, select }){
      try {
        const {data,success} = yield call(queryBankCodeList )
        if (success) {
          yield put({ type: 'updateStore', payload: {bankCodeList:data} });

        }
        
      } catch (e) {
        console.log(e)
      }
    }
    
  }, 

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
